package controller;

import common.Course;
import common.Message;
import common.MessageType;
import common.Topic;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.util.Callback;
import ui.Main;
import util.SetDatePicker;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ResourceBundle;
import java.util.Vector;

public class NewHomeworkController implements Initializable {
    @FXML
    private ListView <String> questionlist;//题目列表
    private ObservableList<String> source= FXCollections.observableArrayList();//数据源
    private Topic topic;
    private Course course;
    public NewHomeworkController(TeacherCourseController teacherCourseController, Course course){
        this.teacherCourseController=teacherCourseController;
        this.course=course;
    }
    @FXML
    public void question(){
        source.add(new String(""));
    }
    @Override
    public void initialize(URL location, ResourceBundle resources){
        questionlist.setItems(source);
        questionlist.setCellFactory(new Callback<javafx.scene.control.ListView<String>, ListCell<String>>() {
            @Override
            public ListCell<String> call(javafx.scene.control.ListView<String> param) {
                return new ListCell<String>() {
                    @Override
                    protected void updateItem(String str, boolean empty) {
                        super.updateItem(str, empty);
                        if (empty || str == null) {
                            setText(null);
                        } else {
                            setText("第"+(getIndex()+1)+"题");
                        }
                    }
                };
            }
        });
        questionlist.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                // 获取双击时选中的项
                String selectedItem = questionlist.getSelectionModel().getSelectedItem();
                if (selectedItem==null) return;
                description.setText(selectedItem);
            }
        });
        SetDatePicker.setDatePickerBefore(publishDate);
        publishDate.setOnMouseClicked(event -> {
            SetDatePicker.setDatePickerDefinition(closeDate,publishDate);
        });
            for(int i=0;i<=9;i++){
                hours.add("0"+i);
                mins.add("0"+i);
                second.add("0"+i);
            }
            for(int i=10;i<=23;i++){
                hours.add(i+"");
                mins.add(i+"");
                second.add(i+"");
            }
            for(int i=24;i<=59;i++){
                mins.add(i+"");
                second.add(i+"");
            }
            hh1.setItems(hours);
            hh2.setItems(hours);
            mm1.setItems(mins);
            mm2.setItems(mins);
            ss1.setItems(second);
            ss2.setItems(second);

    }
    private ObservableList<String> hours=FXCollections.observableArrayList();
    private ObservableList<String> mins=FXCollections.observableArrayList();
    private ObservableList<String> second=FXCollections.observableArrayList();
    @FXML
    private DatePicker publishDate;
    @FXML
    private DatePicker closeDate;
    @FXML
    private TextArea description;
    @FXML
    public void save(){
        int selectedIndex = questionlist.getSelectionModel().getSelectedIndex();
        source.set(selectedIndex,description.getText());
    }
    private TeacherCourseController teacherCourseController;
    @FXML
    private Label dateError;
    @FXML
    private Label timeError;
    @FXML
    private Label titleError;
    @FXML
    private Label questionError;
    @FXML
    private ComboBox<String> hh1,mm1,ss1,hh2,mm2,ss2;
    @FXML
    private TextField title;
    @FXML
    public void publish(){
        if(title.getText().equals("")){
            titleError.setText("标题不能为空");
            return;
        }
        titleError.setText("");
        if(closeDate.getValue()==null||publishDate.getValue()==null){
            dateError.setText("日期不能为空");
            return;
        }
        if(closeDate.getValue().compareTo(publishDate.getValue())<0){
            dateError.setText("截止日期不能早于发布日期");
            return;
        }
        dateError.setText("");
        if(hh1.getValue()==null||mm1.getValue()==null||ss1.getValue()==null||hh2.getValue()==null||mm2.getValue()==null||ss2.getValue()==null){
            timeError.setText("时间不能为空");
            return;
        }
        LocalTime createtime=LocalTime.parse(hh1.getValue()+":"+mm1.getValue()+":"+ss1.getValue());
        LocalTime deadtime=LocalTime.parse(hh2.getValue()+":"+mm2.getValue()+":"+ss2.getValue());
        if(deadtime.compareTo(createtime)<=0&&closeDate.getValue().compareTo(publishDate.getValue())==0){
            timeError.setText("截止时间不能早于发布时间");
            return;
        }
        if(LocalDateTime.of(publishDate.getValue(),createtime).compareTo(LocalDateTime.now())<0){
            timeError.setText("发布时间不能为过去时间");
            return;
        }
        timeError.setText("");
        if(source.size()==0){
            questionError.setText("题目数量为0");
            return;
        }
        questionError.setText("");
        Vector<String> question=new Vector<>();
        for(int i=0;i<source.size();i++){
            question.add(source.get(i));
        }
        topic=new Topic(title.getText(),question,String.valueOf(publishDate.getValue()),String.valueOf(closeDate.getValue()),String.valueOf(createtime),String.valueOf(deadtime));
        topic.setCourse(course);
        Socket socket= Main.userClientService.getSocket();
        Message ms=new Message();
        ms.setState(MessageType.Publish_Work);
        try {
            ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(ms);
            oos.writeObject(topic);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        teacherCourseController.addTopic(topic);
        Stage stage=(Stage) questionError.getScene().getWindow();
        stage.close();
    }
}
